<template>
  <div>
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAddVisible(true)" v-if="$auth('SYSTEM.SYSTEM_ROLE_ADD')"> 添加角色</a-button>
    </div>
    <div class="table">
      <a-table :data-source="data" bordered size="middle">
        <a-table-column key="roleId" title="序号" align="center" >
          <template slot-scope="text, record, index">
            <span>{{ index + 1 }}</span>
          </template>
        </a-table-column>
        <a-table-column key="name" title="角色名称" data-index="name" align="center" />
        <a-table-column key="code" title="角色标识" data-index="code" align="center" />
        <a-table-column key="description" title="描述" data-index="description" align="center" />
        <a-table-column key="action" title="操作" align="center">
          <template slot-scope="text, record">
            <span >
              <a @click="editRow(record, false)" v-if="!$auth('SYSTEM.SYSTEM_ROLE_EDIT') && $auth('SYSTEM.SYSTEM_ROLE_DETAIL')">查看</a>
              <a @click="editRow(record, true)" v-if="$auth('SYSTEM.SYSTEM_ROLE_EDIT')">编辑</a>
              <a-divider type="vertical" v-if="record.code !== 'PROJECT_ADMIN' && $auth('SYSTEM.SYSTEM_ROLE_DELETE')" />
              <a-popconfirm
                title="确定删除本条数据吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="deleteRow(record)"
              >
                <a v-if="record.code !== 'PROJECT_ADMIN' && $auth('SYSTEM.SYSTEM_ROLE_DELETE')">删除</a>
              </a-popconfirm>
            </span>
          </template>
        </a-table-column>
      </a-table>
    </div>
    <!-- <TreeModel
      :visible="addVisible"
      :permission="permission"
      :permissionMP="permissionMP"
      title="新增角色"
      @ok="handconfirm"
      @cancel="addVisible = false"
    /> -->
    <AddRoleNewDrawer
      :visible="addVisible"
      :permission="permission"
      :permissionMP="permissionMP"
      @ok="handconfirm"
      @cancel="addVisible = false"
    />
    <EditRoleNewDrawer
      v-if="editVisible"
      :record="rowRecord"
      ref="treeEdit"
      :visible="editVisible"
      :permission="permission"
      :permissionMP="permissionMP"
      :rolePermission="rolePermission"
      :rolePermissionMP="rolePermissionMP"
      :is-edit="isEdit"
      title="编辑角色"
      @ok="editVisible = false"
      @cancel="editOk()"
    />
    <!-- <TreeModelEdit
      v-if="editVisible"
      :record="rowRecord"
      ref="treeEdit"
      :visible="editVisible"
      :permission="permission"
      :permissionMP="permissionMP"
      :rolePermission="rolePermission"
      :rolePermissionMP="rolePermissionMP"
      title="编辑角色"
      @ok="editVisible = false"
      @cancel="editOk()"
    /> -->
  </div>
</template>

<script>
import { CURRENT_PERMISSION, CURRENT_ROLE } from '@/store/mutation-types'
import TreeModel from './components/addRoleDrawer.vue'
import TreeModelEdit from './components/editRoleDrawer.vue'
import AddRoleNewDrawer from './components/addRoleNewDrawer.vue'
import EditRoleNewDrawer from './components/editRoleNewDrawer.vue'
import { permissionList, permissionListByPro } from '@/api/system/pms.js'
import { getRoleList, userRole, delRole, getRoleListByPro, userRoleByPro, delRoleByPro } from '@/api/system/role.js'
import _ from 'lodash'

const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
  },
  onSelect: (record, selected, selectedRows) => {
    console.log(record, selected, selectedRows)
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows)
  }
}
export default {
  components: {
    TreeModel,
    TreeModelEdit,
    AddRoleNewDrawer,
    EditRoleNewDrawer
  },
  data () {
    return {
      data: [],
      rowRecord: {},
      permission: [],
      permissionMP: [],
      addVisible: false,
      editVisible: false,
      rolePermission: [], // 当前角色拥有的权限
      rolePermissionMP: [],
      rowSelection,
      loading: false,
      expandedRowKeys: [],
      publicPermission: [],
      publicPermissionMP: [],
      isEdit: false
    }
  },
  mounted () {
    this.fetchPermissionList()
    this.fetchList()
    console.log('获取数据 mounted')
  },
  activated () {
    this.fetchList()
    console.log('获取数据 activated')
  },
  methods: {
    refreshListData () {
      this.fetchPermissionList()
    },
    editOk () {
      this.editVisible = false
      this.fetchList()
    },
    // 获取列表信息
    fetchList (params = {}) {
      if (this.$store.getters.project != null) {
        getRoleListByPro({
          proId: this.$store.getters.project.id,
          // proId: 30063,
          systemId: this.$const.SYSTEM_TYPE.PAYMENT.value
        }).then(res => {
          this.data = res
        })
      } else {
        getRoleList().then(res => {
          this.data = res
        })
      }
    },
    // 遍历加参数字段
    setPmsParams (permission) {
      if (permission && permission.length) {
        permission.forEach(item => {
          item.isExpand = false
          item.checked = false
          if (item.child && item.child.length) {
            item.child.forEach(item1 => {
              item1.checked = false
            })
          }
          if (item.children) {
            this.setPmsParams(item.children)
          }
        })
      }
    },
    // 获取权限列表
    fetchPermissionList () {
      if (this.$store.getters.project != null) {
        permissionListByPro({
          proId: this.$store.getters.project.id,
          // proId: 30063,
          systemId: this.$const.SYSTEM_TYPE.PAYMENT.value
        }).then(res => {
          this.permission = res
          this.setPmsParams(this.permission)
          this.publicPermission = []
          this.permission.map(item => {
            // 公共权限不可编辑 (最多三级)
            item.disabled = item.isPublic === 1
            if (item.disabled) {
              this.publicPermission.push(item.id)
            }
            if (item.children != null) {
              item.children.map(sub => {
                sub.disabled = sub.isPublic === 1
                if (sub.disabled) {
                  this.publicPermission.push(sub.id)
                }
                if (sub.children != null) {
                  sub.children.map(child => {
                    child.disabled = child.isPublic === 1
                    if (child.disabled) {
                      this.publicPermission.push(child.id)
                    }
                  })
                }
              })
            }
          })
          console.log('========', this.permission)
        })

        permissionListByPro({
          proId: this.$store.getters.project.id,
          // proId: 30063,
          systemId: this.$const.SYSTEM_TYPE.MP.value
        }).then(res => {
          this.permissionMP = res
          this.setPmsParams(this.permissionMP)
          this.publicPermissionMP = []
          this.permissionMP.map(item => {
            // 公共权限不可编辑 (最多三级)
            item.disabled = item.isPublic === 1
            if (item.disabled) {
              this.publicPermissionMP.push(item.id)
            }
            if (item.children != null) {
              item.children.map(sub => {
                sub.disabled = sub.isPublic === 1
                if (sub.disabled) {
                  this.publicPermissionMP.push(sub.id)
                }
                if (sub.children != null) {
                  sub.children.map(child => {
                    child.disabled = child.isPublic === 1
                    if (child.disabled) {
                      this.publicPermissionMP.push(child.id)
                    }
                  })
                }
              })
            }
          })
          console.log('========', this.permissionMP)
        })
      } else {
        permissionList().then(res => {
          this.permission = res
          this.setPmsParams(this.permission)
          this.publicPermission = []
          this.permission.map(item => {
            // 公共权限不可编辑 (最多三级)
            item.disabled = item.isPublic === 1
            if (item.disabled) {
              this.publicPermission.push(item.id)
            }
            if (item.children != null) {
              item.children.map(sub => {
                sub.disabled = sub.isPublic === 1
                if (sub.disabled) {
                  this.publicPermission.push(sub.id)
                }
                if (sub.children != null) {
                  sub.children.map(child => {
                    child.disabled = child.isPublic === 1
                    if (child.disabled) {
                      this.publicPermission.push(child.id)
                    }
                  })
                }
              })
            }
          })
          console.log('========', this.permission)
        })
      }
    },
    // 确定处理
    handconfirm (value) {
      this.addVisible = false
      this.fetchList()
    },
    handleAddVisible (flag = false) {
      this.setPmsParams(this.permission)
      this.setPmsParams(this.permissionMP)
      // this.addVisible = flag
      this.$store.commit(CURRENT_PERMISSION, {
        permission: this.permission,
        permissionMP: this.permissionMP
      })
      this.$router.push({ path: '/addRole' })
    },
    addPermission (row) {
      console.log(row)
    },
    recurser (target, dataSource, stand) {
      dataSource.forEach(item => {
        if (stand.findIndex(i => i === item.id) >= 0) {
          target.push(item.id)
        }
        if (item.child && item.child.length) {
          item.child.forEach(item1 => {
            if (stand.findIndex(i => i === item1.id) >= 0) {
              target.push(item1.id)
            }
          })
        }
        if (item.children != null && item.children.length > 0) {
          this.recurser(target, item.children, stand)
        }
      })
    },
    // 编辑角色
    editRow (row, flag) {
      this.isEdit = flag
      // debugger
      if (this.$store.getters.project != null) {
        userRoleByPro({
          roleId: row.id,
          proId: this.$store.getters.project.id,
          // proId: 30063,
          systemId: this.$const.SYSTEM_TYPE.PAYMENT.value
        }).then(res => {
          const list = []
          res.forEach(element => {
            list.push(element.pmsId)
          })
          const plist = []
          this.recurser(plist, this.permission, list)

          const plistMP = []
          this.recurser(plistMP, this.permissionMP, list)

          this.rolePermission = _.uniq([...this.publicPermission, ...plist]) // 该用户拥有的权限
          this.rolePermissionMP = _.uniq([...this.publicPermissionMP, ...plistMP]) // 该用户拥有的权限

          console.log('======123123=====', this.rolePermission, this.rolePermissionMP)
          // this.rowRecord = row
          // this.editVisible = true // 获取到后在弹出
          this.toEdit({
            rolePermission: this.rolePermission,
            rolePermissionMP: this.rolePermissionMP,
            isEdit: flag
          }, row)
        })
      } else {
        userRole({
          roleId: row.id,
          systemId: this.$const.SYSTEM_TYPE.PAYMENT.value
        }).then(res => {
          const list = []
          res.forEach(element => {
            list.push(element.pmsId)
          })
          this.rolePermission = _.uniq([...this.publicPermission, ...list]) // 该用户拥有的权限
          // this.rowRecord = row
          // this.editVisible = true // 获取到后在弹出
          this.toEdit({
            rolePermission: this.rolePermission,
            isEdit: flag
          }, row)
        })
      }
    },
    // 跳转到编辑页面
    toEdit (mData, row, flag) {
      this.$store.commit(CURRENT_PERMISSION, {
        permission: this.permission,
        permissionMP: this.permissionMP,
        ...mData
      })
      this.$store.commit(CURRENT_ROLE, row)
      this.$router.push({ path: '/editRole' })
    },
    // 删除事件
    deleteRow (row) {
      const id = row.id
      if (this.$store.getters.project != null) {
        delRoleByPro({
          id,
          proId: this.$store.getters.project.id,
          // proId: 30063,
          systemId: this.$const.SYSTEM_TYPE.PAYMENT.value
        }).then(res => {
          this.$message.success('删除成功')
          this.fetchList()
        })
      } else {
        delRole({
          id
        }).then(res => {
          this.$message.success('删除成功')
          this.fetchList()
        })
      }
    }
  }
}
</script>

<style></style>
